package cn.bs.busuo.account.service.impl;

import cn.bs.busuo.account.dao.persist.repository.IOrderRepository;
import cn.bs.busuo.account.dao.persist.repository.ISightTypeRepository;
import cn.bs.busuo.account.pojo.entity.SightOrder;
import cn.bs.busuo.account.pojo.param.Order;
import cn.bs.busuo.account.pojo.param.Type;
import cn.bs.busuo.account.pojo.vo.OrderVO;
import cn.bs.busuo.account.pojo.vo.TypeVO;
import cn.bs.busuo.account.service.IOrderService;
import cn.bs.busuo.common.enumerator.ServiceCode;
import cn.bs.busuo.common.ex.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private IOrderRepository orderRepository;
    @Autowired
    private ISightTypeRepository sightTypeRepository;

    @Override
    public void addOrder(Order order) {
// 先查询是否有未支付的订单,有则叫它给钱
        OrderVO orderVO = orderRepository.selectOrder(order);
        if (orderVO != null && orderVO.getOrderState() == 1) {
            String message = "对于该类门票你有未支付的订单！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        //        查询用户名,景点id,景点门票名是否存在
        Type type = new Type();
        type.setSightsId(order.getSightsId());
        type.setTicketName(order.getTicketName());
//        根据景点id和门票类型查询数据
        TypeVO typeVO = sightTypeRepository.selectType(type);
        if (typeVO == null) {
            String message = "购买失败，没有该类型门票！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
//         根据数量算出总价
        Long price = typeVO.getSaleUnitPrice();
        SightOrder sightOrder = new SightOrder();
        BeanUtils.copyProperties(order, sightOrder);
        Integer goodsNum = order.getGoodsNum();
        Long totalPrice = price * goodsNum;
//        将long类型转换成BigDecimal类型
        BigDecimal bigDecimal = new BigDecimal(totalPrice);
        sightOrder.setTotalPrice(bigDecimal);
        sightOrder.setOrderState(1);
        orderRepository.addOrder(sightOrder);
    }
//    todo 删除订单
//    todo 付款
//    todo 更改订单状态
}
